//给定一个链表和一个特定值 x，对链表进行分隔，使得所有小于 x 的节点都在大于或等于 x 的节点之前。 
//
// 你应当保留两个分区中每个节点的初始相对位置。 
//
// 
//
// 示例: 
//
// 输入: head = 1->4->3->2->5->2, x = 3
//输出: 1->2->2->4->3->5
// 
// Related Topics 链表 双指针 
// 👍 259 👎 0

package leetcode.editor.cn;

import common.bean.ListNode;
import common.util.MyUtil;

/**
 * Java：分隔链表
 *
 * @author changgui
 */
@SuppressWarnings("all")
public class P86_PartitionList {
    public static void main(String[] args) {
        Solution solution = new P86_PartitionList().new Solution();
        ListNode listNode = solution.partition(MyUtil.createNode(1, 4, 3, 2, 5, 2), 3);
        MyUtil.printListNode(listNode);

    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public ListNode partition(ListNode head, int x) {
            if (head == null) {
                return null;
            }
            // 小于x的链表头
            ListNode lowPreHead = new ListNode(0), ltmp = lowPreHead;
            // 大于等于x的链表头
            ListNode highPreHead = new ListNode(0), htmp = highPreHead;
            // 小于x的节点放在lowPreHead，其他放在highPreHead，注意highPreHead最后节点置为null
            for (ListNode curr = head; curr != null; ) {
                ListNode tmp = curr.next;
                if (curr.val < x) {
                    ltmp.next = curr;
                    ltmp = ltmp.next;
                } else {
                    htmp.next = curr;
                    htmp = htmp.next;
                    htmp.next = null;
                }
                curr = tmp;
            }
            // 两链表连接
            ltmp.next = highPreHead.next;
            return lowPreHead.next;
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)

}